package com.ews.onlineexchange.service;

import java.util.ArrayList;
import java.util.List;

import javax.enterprise.inject.Model;
import javax.inject.Inject;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;

import com.ews.onlineexchange.model.Bulletin;
import com.ews.onlineexchange.model.ServiceSupplier;
import com.ews.onlineexchange.model.Trade;
import com.ews.onlineexchange.model.TradeRating;

@Model
public class RatedTradeList extends EntityQuery<Trade> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public RatedTradeList() {
		super();
	}

	@Inject
	UserService		userService;

	private String	username;

	public String getUsername() {
		return username;
	}

	public void setUsername( String username ) {
		this.username = username;
	}

	@Override
	protected Order[] getOrderArray( CriteriaBuilder cb, Root<Trade> entity ) {
		List<Order> orderList = new ArrayList<Order>();
		Join<Trade, Bulletin> bulletin = entity.join( "bulletin" );
		Join<Trade, TradeRating> tradeRating = entity.join( "tradeRating" );
		orderList.add( cb.desc( tradeRating.get( "createDate" ) ) );
		orderList.add( cb.desc( bulletin.get( "doneTime" ) ) );
		return orderList.toArray( new Order[orderList.size()] );
	}

	@Override
	protected List<Predicate> getRestrictions( CriteriaBuilder cb, Root<Trade> entity ) {
		List<Predicate> restrictions = super.getRestrictions( cb, entity );
		restrictions.add( cb.isTrue( entity.<Boolean>get( "hasVerify" ) ) );
		Join<Trade, Bulletin> bulletin = entity.join( "bulletin" );
		restrictions.add( cb.isTrue( bulletin.<Boolean>get( "applyDone" ) ) );
		restrictions.add( cb.isTrue( bulletin.<Boolean>get( "done" ) ) );
		Join<Bulletin, Trade> successTrade = bulletin.join( "successTrade" );
		restrictions.add( cb.equal( entity.get( "id" ), successTrade.get( "id" ) ) );

		Join<Trade, TradeRating> tradeRating = entity.join( "tradeRating" );
		restrictions.add( cb.equal( entity.get( "id" ), tradeRating.get( "trade" ).get( "id" ) ) );

		Join<Trade, ServiceSupplier> supplier = entity.join( "supplier" );
		restrictions.add( cb.equal( supplier.get( "username" ), getUsername() ) );

		String projectName = (String) getParameterValues().get( "projectName" );
		if ( !StringUtils.isBlank( projectName ) )
			restrictions.add( cb.like( bulletin.get( "projectName" ), getStringRestriction( projectName ) ) );

		String serialNumber = (String) getParameterValues().get( "serialNumber" );
		if ( !StringUtils.isBlank( serialNumber ) )
			restrictions.add( cb.like( bulletin.get( "serialNumber" ), getStringRestriction( serialNumber ) ) );
		System.out.println("_------------------");
		return restrictions;
	}

}
